import React, { useState } from 'react'
import './shopcartList.scss'
export default function ShopCartList() {
    const [list, setList] = useState([
        {
            id: 1,
            name: '苹果',
            price: 5.2,
            num: 2,
            flag:true
        },
        {
            id: 2,
            name: '香蕉',
            price: 3.2,
            num: 1,
            flag:false
        },
        {
            id: 3,
            name: '葡萄',
            price: 8.2,
            num: 1,
            flag:false
        }
    ])
    const changeNum = (op, index) => {
        console.log('op', op, 'index', index);
        switch (op) {
            case '+':
                list[index].num++
                break;
            case '-':
                list[index].num--
                break;
        }
        setList([...list])
    }
    const handleInputName=(e,index)=>{
      list[index].num=e.target.value
      setList([...list])
    }
    const handleChecked=(e,index)=>{
        console.log('e',e.target.checked);
        console.log('index',index);
        list[index].flag=e.target.checked
        setList([...list])
    }
    const getTotal=()=>{
        return list.filter(item=>item.flag).reduce((pre,cur)=>pre+cur.price*cur.num,0).toFixed(2)
    }

    return (

        <div>
            <table>
                <thead>
                    <tr>
                        <td>编号</td>
                        <td>名称</td>
                        <td>价格</td>
                        <td>数量</td>
                        <td>小计</td>
                    </tr>
                </thead>
                <tbody>
                    {
                        list.map((item, index) => <tr key={item.id}>
                            <td>
                                <input type="checkbox" checked={item.flag} onChange={(e)=>{handleChecked(e,index)}}/>
                            </td>
                            <td>{item.name}</td>
                            <td>{item.price}</td>
                            <td>
                                <button onClick={() => { changeNum('-', index) }}>-</button>
                                <input type="text" value={item.num} onChange={(e)=>{handleInputName(e,index)}}/>
                                <button onClick={() => { changeNum('+', index) }}>+</button>
                            </td>
                            <td>{(item.num * item.price).toFixed(2)}</td>
                        </tr>)
                    }
                </tbody>
                <tfoot>
                    <tr>
                        <td colSpan={5}>
                            总价:{getTotal()}
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>
    )
}
